package cn.iocoder.yudao.module.member.service.siteagent;


import cn.iocoder.yudao.module.member.controller.admin.siteagent.vo.SiteAgentVo;
import cn.iocoder.yudao.module.member.convert.agentsite.SiteAgentConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.agentconfig.SiteAgentDO;
import cn.iocoder.yudao.module.member.dal.mysql.configsite.SiteAgentMapper;
import cn.iocoder.yudao.module.member.service.agentsite.SiteAgentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

@Service
@Validated
@Slf4j
public class SiteAgentServiceImpl implements SiteAgentService {

    @Resource
    private SiteAgentMapper siteAgentMapper;

    /**
     * 保存贴牌配置
     * 当前配置具有唯一属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveConfig(SiteAgentVo saveReqVO) {
        // 判断是否已有配置
        Long count = siteAgentMapper.selectCount();
        if (count > 0) {
            throw new RuntimeException("当前贴牌已存在配置,请修改");
        }
        // 这里可根据业务自动生成 siteCode/ID 等
        // 示例：siteCode 必填，不自动生成
        SiteAgentDO convert = SiteAgentConvert.INSTANCE.convert(saveReqVO);
        convert.setId(null);
        siteAgentMapper.insert(convert);
    }

    /**
     * 获取贴牌配置详细信息
     */
    @Override
    public SiteAgentVo getConfig() {
        List<SiteAgentDO> list = siteAgentMapper.selectList();
        if (list.isEmpty()) {
            return null;
        }
        return SiteAgentConvert.INSTANCE.convert(list.get(0));
    }

    /**
     * 更新贴牌配置：删除原有再插入
     */
    @Override
    @Transactional
    public SiteAgentVo updateConfig(SiteAgentVo vo) {
        SiteAgentDO siteAgentDO = siteAgentMapper.selectById(vo.getId());
        if (siteAgentDO == null) {
            throw new RuntimeException("贴牌配置不存在");
        }
        siteAgentMapper.deleteById(siteAgentDO.getId());
        this.saveConfig(vo);
        return vo;
    }
}
